﻿using UnityEngine;
using UnityEngine.UI;
using TBFramework;
using System;
using System.Text;
public class MultipleChoiceQuestionComponent : UIParentClass
{
    Action<string> action;
    MultipleChoiceQuestion multipleChoiceQuestion;

    public string[] options;
    public override void Init<T>(T values, Action<string> _action)
    {
        action = _action;
        multipleChoiceQuestion = values as MultipleChoiceQuestion;
        Transform tempObj = transform.GetChild(0).GetChild(1);

        transform.GetChild(0).GetChild(0).GetComponent<Text>().text = multipleChoiceQuestion.question;

        for (int i = 0; i < tempObj.childCount; i++)
        {
            tempObj.GetChild(i).gameObject.SetActive(false);
        }
        for (int i = tempObj.childCount; i < multipleChoiceQuestion.options.Count; i++)
        {
            Instantiate(tempObj.GetChild(0).gameObject, tempObj);
        }
        options = new string[multipleChoiceQuestion.options.Count];
        
        for (int i = 0; i < multipleChoiceQuestion.options.Count; i++)
        {
            tempObj.GetChild(i).GetChild(0).GetComponent<Toggle>().isOn = false;
            tempObj.GetChild(i).GetChild(1).GetComponent<Text>().text = multipleChoiceQuestion.options[i];
            tempObj.GetChild(i).gameObject.SetActive(true);
            tempObj.GetChild(i).name = (i + 1).ToString();

            tempObj.GetChild(i).GetComponent<Button>().onClick.RemoveAllListeners();
            var toggle = tempObj.GetChild(i).GetChild(0).GetComponent<Toggle>();
            var temp = (i + 1).ToString();
            var i1 = i;

            toggle.onValueChanged.RemoveAllListeners();
            toggle.onValueChanged.AddListener((value) =>
            {
                options[i1] = value ? temp : "";
            });
            tempObj.GetChild(i).GetComponent<Button>().onClick.AddListener(() =>
            {
                toggle.isOn = !toggle.isOn;
                options[i1] = toggle.isOn ? temp : "";
            });
        }
    }
    public void ButtonClick()
    { 
        StringBuilder sb = new StringBuilder();
        bool first = true;

        for (int i = 0; i < options.Length; i++)
        {
            if (!string.IsNullOrEmpty(options[i]))
            {
                if (!first)
                {
                    sb.Append(",");
                }
                sb.Append(options[i]);
                first = false;
            }
        }

        string combinedOptions = sb.ToString();
        action(combinedOptions);
    }
}
